﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UFPC.Models;

namespace UFPC.Controllers
{
    [Authorize]
    public class ProductController : Controller
    {
        private IUfpcRepository _repository;

        public ProductController() : this(new UfpcRepository())
        {

        }

        public ProductController(IUfpcRepository repository)
        {
            _repository = repository;
        }

        //
        // GET: /Product/

        public ActionResult Index()
        {
            return View(_repository.ListProducts());
        }

        //
        // GET: /Product/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Product/Create

        [HttpPost]
        public ActionResult Create([Bind(Exclude="ProductId")]Product newProduct)
        {
            
            if (ModelState.IsValid)
            {
                _repository.AddProduct(newProduct);
                _repository.Save();

                return RedirectToAction("Index");
            }

            return View();
        }
        
        //
        // GET: /Product/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View(_repository.ProductDetails(id));
        }

        //
        // POST: /Product/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            Product product = _repository.ProductDetails(id);

            try
            {
                UpdateModel(product);
                _repository.Save();

                return RedirectToAction("Index");
            }
            catch
            {
                return View(_repository.ProductDetails(id));
            }
        }

        //
        // GET: /Product/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View(_repository.ProductDetails(id));
        }

        //
        // POST: /Product/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            Product product = _repository.ProductDetails(id);

            _repository.DeleteProduct(product);
            _repository.Save();

            return RedirectToAction("Index");
        }
    }
}
